package com.tbynet.wordpress.admin;

import java.util.LinkedHashMap;
import java.util.Map;

import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;
import com.tbynet.wordpress.model.Usermeta;
import com.tbynet.wordpress.model.Users;
import com.tbynet.wordpress.service.UserService;

public class AdminInterceptor implements Interceptor {

	@Inject
	UserService userService;
	
	@Override
	public void intercept(Invocation inv) {
		AdminController ctr = (AdminController)inv.getController();
		
		Users user = null;
		String sessionId = ctr.getCookie(Users.sessionIdName);
		if (null != sessionId) {
			user = userService.getLoginUserBySessionId(sessionId);
		}
		
		if (null != user) {
			Usermeta permissions = userService.getUsermeta(user.getID(), "permissions");
			try {
				if(null == permissions) {
					ctr.set("error", "permission");
					ctr.render("../error.html", 403);
					return;
				}
				
				Map<String, Boolean> map = permissions.getPermissions().toLinkedHashMap();
//				if(null == map || map.isEmpty() || false == map.containsKey("activate_plugins")) {
//					ctr.set("error", "permission");
//					ctr.render("../error.html", 403);
//					return;
//				}
			} catch(Exception e) {
				e.printStackTrace();
			}
			// 用户登录
			ctr.set(Users.loginUserCacheName, user);
		} else {
			ctr.removeCookie(Users.sessionIdName); // 删除无效cookie
			String queryString = inv.getController().getRequest().getQueryString();
			if (StrKit.isBlank(queryString)) {
				ctr.redirect("/admin/login?redirect_url=" + inv.getActionKey());
			} else {
				ctr.redirect("/admin/login?redirect_url=" + inv.getActionKey() + "?" + queryString);
			}
			return;
		}
		
		ctr.set("ACTION_KEY", inv.getActionKey());
		
		inv.invoke();
	}

}
